package com.mlethe.library.socialtool.core;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

import com.mlethe.library.socialtool.callback.ShareActionListener;
import com.mlethe.library.socialtool.entity.Share;
import com.mlethe.library.socialtool.entity.ShareImage;
import com.mlethe.library.socialtool.entity.ShareText;
import com.mlethe.library.socialtool.entity.ShareVideo;
import com.mlethe.library.socialtool.entity.ShareWeb;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.MultiImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.VideoSourceObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.common.UiError;
import com.sina.weibo.sdk.openapi.IWBAPI;
import com.sina.weibo.sdk.share.WbShareCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 微博分享工具类
 *
 * @author Mlethe
 */
public class WeiboShare {

    private static ShareActionListener mListener;

    private static ShareCallback mShareCallback = new ShareCallback();

    public static void setShareActionListener(ShareActionListener listener) {
        mListener = listener;
    }

    /**
     * 分享回调
     * 重要：发起分享的 Activity 必须重写 onNewIntent 或 onActivityResult
     *
     * @param data
     */
    public static void onActivityResult(Weibo weibo, Intent data) {
        IWBAPI api = weibo.getApi();
        if (api != null) {
            api.doResultIntent(data, mShareCallback);
        }
    }

    /**
     * 分享
     *
     * @param context
     * @param weibo
     * @param shares 文本-ShareText、网页-ShareWeb、图片-ShareImage、视频-ShareVideo
     */
    public static void share(final Context context, final Weibo weibo, final Share... shares) {
        if (!weibo.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.WEIBO);
                mListener = null;
            }
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                if (shares != null) {
                    for (Share share : shares) {
                        if (share instanceof ShareText) {
                            weiboMessage.textObject = getTextObject((ShareText) share);
                        } else if (share instanceof ShareImage) {
                            weiboMessage.imageObject = getImageObject(context, (ShareImage) share);
                        } else if (share instanceof ShareWeb) {
                            weiboMessage.mediaObject = getWebpageObject(context, (ShareWeb) share);
                        } else if (share instanceof ShareVideo) {
                            weiboMessage.videoSourceObject = getVideoSourceObject((ShareVideo) share);
                            TextObject textObject = new TextObject();
                            textObject.text = share.getTitle();
                            weiboMessage.textObject = textObject;
                        }
                    }
                }
                weibo.getApi().shareMessage(weiboMessage, false);
            }
        }).start();
    }

    /**
     * 分享多图
     *
     * @param weibo
     * @param paths
     * @param shares 文本->ShareText，网页->ShareWeb
     */
    public static void share(final Context context, final Weibo weibo, final List<String> paths, final Share... shares) {
        if (!weibo.isAppInstalled()) {
            if (mListener != null) {
                mListener.onNotInstalled(Platform.WEIBO);
                mListener = null;
            }
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<Uri> pathList = new ArrayList<>();
                for (String path : paths) {
                    pathList.add(Uri.fromFile(new File(path)));
                }
                MultiImageObject multiImageObject = new MultiImageObject();
                multiImageObject.imageList = pathList;
                WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
                if (shares != null) {
                    for (Share share : shares) {
                        if (share instanceof ShareText) {
                            weiboMessage.textObject = getTextObject((ShareText) share);
                        } else if (share instanceof ShareWeb) {
                            weiboMessage.mediaObject = getWebpageObject(context, (ShareWeb) share);
                        }
                    }
                }
                weiboMessage.multiImageObject = multiImageObject;
                weibo.getApi().shareMessage(weiboMessage, false);
            }
        }).start();
    }

    /**
     * 获取文本分享对象
     *
     * @param share
     * @return
     */
    private static TextObject getTextObject(ShareText share) {
        TextObject textObject = new TextObject();
        textObject.text = share.getTitle();
        return textObject;
    }

    /**
     * 获取视频分享对象
     *
     * @param share
     * @return
     */
    private static VideoSourceObject getVideoSourceObject(ShareVideo share) {
        VideoSourceObject videoSourceObject = new VideoSourceObject();
        videoSourceObject.videoPath = Uri.fromFile(new File(share.getVideoPath()));
        return videoSourceObject;
    }

    /**
     * 获取图片分享对象
     *
     * @param context
     * @param share
     * @return
     */
    private static ImageObject getImageObject(Context context, ShareImage share) {
        Bitmap bitmap = null;
        byte[] thumbData = null;
        String imagePath = null;
        if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {
            // 网络图片
            bitmap = Util.url2bitmap(share.getImageUrl());
        } else if (share.getImagePath() != null && !"".equals(share.getImagePath())) {
            // 本地图片
            imagePath = share.getImagePath();
        } else if (share.getBitmap() != null) {
            bitmap = share.getBitmap();
        } else if (share.getImageData() != null) {
            thumbData = share.getImageData();
        } else if (share.getDrawableId() != 0) {
            bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
        }
        ImageObject imageObject = new ImageObject();
        if (bitmap != null) {
            imageObject.setImageData(bitmap);
            if (bitmap != null) {
                bitmap.recycle();
            }
        } else if (imagePath != null) {
            imageObject.imagePath = imagePath;
        } else if (thumbData != null) {
            imageObject.imageData = thumbData;
        }
        return imageObject;
    }

    /**
     * 获取网页分享对象
     *
     * @param context
     * @param share
     * @return
     */
    private static WebpageObject getWebpageObject(Context context, ShareWeb share) {
        Bitmap thumbBmp = getBitmap(context, share);
        WebpageObject webObject = new WebpageObject();
        webObject.identify = UUID.randomUUID().toString();
        webObject.title = share.getTitle();
        webObject.description = share.getDesc();
        // 设置 Bitmap 类型的图片到视频对象里
        // 设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        if (thumbBmp != null) {
            ByteArrayOutputStream os = null;
            try {
                os = new ByteArrayOutputStream();
                thumbBmp.compress(Bitmap.CompressFormat.JPEG, 85, os);
                webObject.thumbData = os.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                thumbBmp.recycle();
                try {
                    if (os != null) {
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            webObject.thumbData = share.getImageData();
        }
        webObject.actionUrl = share.getUrl();
        webObject.defaultText = "分享网页";
        return webObject;
    }

    /**
     * 获取bitmap
     *
     * @param share
     * @return
     */
    private static Bitmap getBitmap(Context context, Share share) {
        Bitmap thumbBmp = null;
        if (share.getImagePath() != null && !"".equals(share.getImagePath())) {
            // 本地图片
            Bitmap bitmap = BitmapFactory.decodeFile(share.getImagePath());
            thumbBmp = Util.bitmapFormat(bitmap);
            if (bitmap != null) {
                bitmap.recycle();
            }
        } else if (share.getImageUrl() != null && !"".equals(share.getImageUrl())) {
            // 网络图片
            thumbBmp = Util.bitmapFormat(Util.url2bitmap(share.getImageUrl()));
        } else if (share.getBitmap() != null) {
            // 本地图片
            thumbBmp = Util.bitmapFormat(share.getBitmap());
        } else if (share.getDrawableId() != 0) {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), share.getDrawableId());
            thumbBmp = Util.bitmapFormat(bitmap);
            if (bitmap != null) {
                bitmap.recycle();
            }
        }
        return thumbBmp;
    }

    /**
     * 回调处理类
     */
    private static class ShareCallback implements WbShareCallback {

        @Override
        public void onComplete() {
            if (mListener != null) {
                mListener.onComplete(Platform.WEIBO);
                mListener = null;
            }
        }

        @Override
        public void onError(UiError uiError) {
            if (mListener != null) {
                mListener.onFail(Platform.WEIBO);
                mListener = null;
            }
        }

        @Override
        public void onCancel() {
            if (mListener != null) {
                mListener.onCancel(Platform.WEIBO);
                mListener = null;
            }
        }
    }
}
